Virtual Methods
A virtual method is a method that is declared as virtual in a base class and redefined in one or more derived classes. Thus, each derived class can have its own version of a virtual method. You declare a method as virtual inside a base class by preceding its declaration with the keyword virtual. When a virtual method is redefined by a derived class, the override modifier is used. a virtual method cannot be specified as static or abstract.
Program on Virtual methods and polymorphism
using System;
class abc
{
protected int a;
public abc(int x)
{
a = x;
}
virtual public void put()
{
Console.WriteLine("Value of a" + a);
}
}
class xyz : abc
{
int b;
public xyz(int x, int y): base(x)
{
b = y;
}
public override void put()
{
Console.WriteLine("Value of a" + a);
Console.WriteLine("value of b" + b);
}
}
class sample
{
public static void Main(String[] args)
{
abc x = new abc(5);
xyz y = new xyz(3,6);
abc z;
z = x;
z.put();
z = y;
z.put();
}
}
Program to find the area of triangle ,circle,simple interest using polymorphisam.
using System;
class abc
{
protected int b,h;
public abc(int x,int y)
{
b=x;
h=y;
}
virtual public void put()
{
Console.WriteLine("Traiangle"+(b*h)/2);
}
}
class xyz : abc
{
protected int r;
public xyz(int x, int y,int z): base(x,y)
{
r=z;
}
public override void put()
{
Console.WriteLine ("Circle"+(22/7*r*r));
}
}
class pqr:xyz
{
int p,t;
public pqr(int x,int y,int z,int m,int n,int o):base(x,y,z)
{
p=m;
t=n;
r=o;
}
public override void put()
{
Console.WriteLine ("Simple interest"+(p*t*r)/100);
}
}
class sample
{
public static void Main(String[] args)
{
abc x = new abc(5,2);
xyz y = new xyz(3,6,5);
pqr z=new pqr (5,3,2,1000,3,2);
abc m;
m=x;
m.put ();
m=y;
m.put ();
m=z;
m.put ();
}
}
Program on hierarchical inheritance and polymorphism
using System;
class abc
{
protected int b,h;
public abc(int x,int y)
{
b=x;
h=y;
}
virtual public void put()
{
Console.WriteLine("Traiangle"+(b*h)/2);
}
}
class xyz : abc
{
protected int r;
public xyz(int x, int y,int z): base(x,y)
{
r=z;
}
public override void put()
{
Console.WriteLine ("Circle"+(22/7*r*r));
}
}
class pqr:abc
{
int p,t,r;
public pqr(int x,int y,int z,int m,int n):base(x,y)
{
p=z;
t=m;
r=n;
}
public override void put()
{
Console.WriteLine ("Simple interest"+(p*t*r)/100);
}
}
class sample
{
public static void Main(String[] args)
{
abc x = new abc(5,2);
xyz y = new xyz(3,6,5);
pqr z = new pqr(5, 6, 1000, 10, 5);
abc m;
m=x;
m.put ();
m=y;
m.put ();
m=z;
m.put ();
}
}